package com.cty.B_SpecialDataStructures.A_Stack.StackArray;

import com.cty.F_common.DataItem;

/**
 * @Auther: cty
 * @Date: 2020/6/13 22:16
 * @Description: 数组实现栈
 * 应用场景：
 *      数据量可预测或内存充足时使用
 * 重要操作：
 *      ① peek(): DataItem    O(1)
 *      ② push(DataItem): boolean    O(1)
 *      ③ pop(): DataItem    O(1)
 * @version: 1.0
 */
public class StackArray {
    private int maxSize;
    private DataItem[] array;
    private int top;

    public StackArray(int maxSize){
        this.maxSize = maxSize;
        array = new DataItem[maxSize];
        top = -1;
    }

    public boolean isEmpty(){
        return (top == -1);
    }

    public boolean isFull(){
        return (top == maxSize-1);
    }

    public int size(){
        return (top + 1);
    }

    public void displayStack(){
        for(int i=0; i<=top; i++)
            System.out.print(array[i].getKey() + " ");
        System.out.println();
    }

    /**
     * 查看栈顶  O(1)
     * @return
     *      DataItem
     *      null
     */
    public DataItem peek(){
        if(isEmpty())
            return null;

        return array[top];
    }

    /**
     * 压栈  O(1)
     * @param item
     * @return
     *      true
     *      false
     */
    public boolean push(DataItem item){
        if(isFull())
            return false;

        array[++top] = item;
        return true;
    }

    /**
     * 出栈  O(1)
     * @return
     *      DataItem
     *      null
     */
    public DataItem pop(){
       if(isEmpty())
           return null;

       return array[top--];
    }

}  // end StackArray{}
